# -*- coding: utf-8 -*-
from win32com import client
import VBAPI
from tkinter import *
from tkinter import ttk, filedialog, messagebox, scrolledtext
import pandas as pd


CREO_APP = 'C:/Program Files/PTC/Creo 6.0.0.0/Parametric/bin/parametric.exe'
INPUT_DIR = 'E:/00A30/002testvbapi/'

win = Tk()
win.title("批量参数操作")
win.rowconfigure(0, weight='2')
win.columnconfigure(0, weight='1')

frame1 = ttk.Frame(win, padding='3 3 12 12')
frame1.grid(row=0, column=0, sticky=(N, W, E, S))

ttk.Label(frame1, text="Creo路径", width=15).grid(row=0, column=0, padx=5, pady=5, stick=E)
e_app = ttk.Entry(frame1, width=55)
e_app.grid(row=0, column=1)
e_app.insert('0', CREO_APP)

ttk.Label(frame1, text="文件目录", width=15).grid(row=1, column=0, padx=5, pady=5, stick=E)
e_dir = ttk.Entry(frame1, width=55)
e_dir.grid(row=1, column=1)
e_dir.insert('0', INPUT_DIR)

ttk.Label(frame1, text="参数文件", width=15).grid(row=2, column=0, padx=5, pady=5, stick=E)
e_params = ttk.Entry(frame1, width=55)
e_params.grid(row=2, column=1)

frame2 = ttk.Frame(win, padding='3 3 12 12')
frame2.grid(row=1, column=0, stick=(N, W, E, S))

st_message = scrolledtext.ScrolledText(frame2, width=180, height=30)
st_message.grid(row=1, column=0, columnspan=12)

#global df

def chooseapp():
    filename = filedialog.askopenfilename()
    if filename != "":
        CREO_APP = filename
        e_app.delete('0', 'end')
        e_app.insert('0', CREO_APP)

def choosedir():
    dirname = filedialog.askdirectory()
    if dirname != "":
        INPUT_DIR = dirname
        e_dir.delete('0', 'end')
        e_dir.insert('0', INPUT_DIR)

def chooseparams():
    params = filedialog.askopenfilename(filetypes=(('csv files', '*.csv'), ('excel files', '*.xlsx;*.xls')))
    if params != "":
        e_params.delete('0', 'end')
        e_params.insert('0', params)

def export_excel():
    global df
    data = {'MODEL_NAME': ['', 'part001.prt'],
            "PTC_COMMON_NAME": ['Ex_string', 'test'],
            "MEMBER_NAME": ['Ex_string', 'test'],
            "MATERIAL": ['Ex_string', 'test'],
            "DRAWING_NUMBER": ['Ex_string', 'test'],
            "ENGLISH_NAME": ['Ex_string', 'test'],
            "PDRAWN_BY": ['Ex_string', 'test']}
    df = pd.DataFrame(data)
    filename = INPUT_DIR + 'MultiAddParameter.csv'
    df.to_csv(filename, index=False)
    e_params.delete('0', 'end')
    e_params.insert('0', filename)

def read_excel():
    global df
    if e_params.get() != '':
        filename = e_params.get()
        df = pd.read_csv(filename, sep=',', encoding='gbk', )
        pd.set_option('display.width', None) #设置数据展示宽度
        st_message.insert('end', "参数文件已读取！" + '\n')
        st_message.insert('end', df.iloc[0:])
        st_message.insert('end', '\n')
        st_message.see(END)
    else:
        messagebox.showinfo('提示', '请选择参数文件！')

def add_params():
    global df
    if df.shape[0] > 0:

        cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
        AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
        AsyncConnection.Session.ChangeDirectory(INPUT_DIR)
        st_message.insert('end', '开始添加参数：\n')
        st_message.insert('end', '{0:<25}'.format('Model Name'))
        st_message.see(END)
        #输出参数名
        for i in range(0, df.shape[1]-1):
            para_name = df.iloc[[0], [i+1]].keys()[0]
            st_message.insert('end', '{0:<25}'.format(para_name))
        st_message.insert('end', '\n')

        for i in range(0, df.shape[0] - 1):
            filename = df.iloc[i+1, 0]

            #AsyncConnection.Session.ChangeDirectory(INPUT_DIR)
            #model = AsyncConnection.Session.GetModelFromFileName(filename)


            ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
            #mdlDescr = ModelDescriptor.Create(getattr(VBAPI.constants, "EpfcMDL_PART"), "", None)
            #mdlDescr.Path = INPUT_DIR + filename
            mdlDescr = ModelDescriptor.CreateFromFileName(filename)
            RetrieveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
            options = RetrieveModelOptions.Create()
            options.AskUserAboutReps = False
            model = AsyncConnection.Session.RetrieveModelWithOpts(mdlDescr, options)


            st_message.insert('end', '{0:<25}'.format(filename))
            for j in range(0, df.shape[1]-1):
                paraname = df.iloc[[i+1], [j+1]].keys()[0]
                paratype = df.iloc[0, j+1]
                paraval = df.iloc[i+1, j+1]
                if paratype == "Ex_string":
                    iparaval = client.Dispatch(VBAPI.CMpfcModelItem).CreateStringParamValue(paraval)
                else:
                    iparaval = client.Dispatch(VBAPI.CMpfcModelItem).CreateNoteParamValue(paraval)
                parameter = model.GetParam(paraname)
                if parameter != None:
                    if paraname != 'PTC_COMMON_NAME':
                        parameter.Delete()
                        model.CreateParam(paraname, iparaval)
                    else:
                        parameter.Value = iparaval
                st_message.insert('end', '{0:<25}'.format(paraval))
            model.save()
            #st_message.insert('end', "参数名：" + paraname + '\t' + "参数值：" + paraval + '\t' + "参数类型：" + paratype + '\n')
            st_message.insert('end', '\n')
            st_message.see(END)
            win.update()
        AsyncConnection.End()
        st_message.insert('end', '参数已全部添加')
        st_message.see(END)




ttk.Button(frame1, text="选择文件", width=15, command=chooseapp).grid(row=0, column=2, padx=5, pady=5)
ttk.Button(frame1, text="选择目录", width=15, command=choosedir).grid(row=1, column=2, padx=5, pady=5)
ttk.Button(frame1, text="选择文件", width=15, command=chooseparams).grid(row=2, column=2, padx=5, pady=5)
ttk.Button(frame2, text="输出模板", width=15, command=export_excel).grid(row=0, column=0, padx=5, pady=5)
ttk.Button(frame2, text="读取参数", width=15, command=read_excel).grid(row=0, column=1, padx=5, pady=5)
ttk.Button(frame2, text="添加参数", width=15, command=add_params).grid(row=0, column=2, padx=5, pady=5)

win.mainloop()
